package com.rambler.common.core.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rambler.common.core.dto.UserDTO;
import com.rambler.common.core.entity.SystemUser;
import com.rambler.common.core.mapper.SystemUserMapper;
import com.rambler.common.utils.IDUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author suhao
 * @date 2025/7/28
 * @description
 */
@Service
public class SystemUserService extends ServiceImpl<SystemUserMapper, SystemUser> {

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();


    /**
     * 用户登录验证
     *
     * @param request 登录请求参数，包含用户名和密码
     * @return 验证通过的系统用户对象
     * @throws RuntimeException 当用户不存在或密码错误时抛出异常
     */
    public SystemUser login(UserDTO request) {
        // 根据用户名查询用户信息
        SystemUser user = this.baseMapper.selectOne(
                new QueryWrapper<SystemUser>().eq("username", request.getUsername())
        );

        // 验证用户是否存在且未被删除
        if (user == null || user.getDelFlag() == 1) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码是否正确
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        return user;
    }

    public void register(UserDTO dto) {
        SystemUser exist = this.baseMapper.selectOne(
                new QueryWrapper<SystemUser>().eq("username", dto.getUsername())
        );
        if (exist != null) {
            throw new RuntimeException("用户名已存在");
        }

        SystemUser user = new SystemUser();
        user.setId(IDUtil.randomUUID());
        user.setUsername(dto.getUsername());
        user.setPassword(passwordEncoder.encode(dto.getPassword()));
        user.setStatus(1);
        user.setDelFlag(0);

        this.baseMapper.insert(user);
    }


}
